package com.situ.stl.controller;

import com.situ.stl.entity.Course;
import com.situ.stl.entity.Result;
import com.situ.stl.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** 
 * Controller层 - 课程
 */
@RestController 
@RequestMapping( value = "/course")
public class CourseController{

    /** 
     */
    @Autowired 
    private CourseService courseService;

    /** 
     * add
     */
    @PostMapping 
    public Result add(@RequestBody Course course) {
        try {
            courseService.add(course);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /** 
     * remove
     */
    @DeleteMapping ("/{id}")
    public Result remove(@PathVariable("id") Integer id) {
        try {
            courseService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /** 
     * edit
     */
    @PutMapping 
    public Result edit( @RequestBody Course course) {
        try {
            courseService.edit(course);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /** 
     * getAll
     */
    @GetMapping 
    public Result getAll( Integer page, Integer limit, Course course) {
        if ( page == null && limit == null) {
        	return Result.success(courseService.search(course));
        } else {
        	return Result.success(courseService.searchByPage(page, limit, course));
        }
    }

    /** 
     * getById
     */
    @GetMapping( value = "/{id}") 
    public Result getById( @PathVariable( value = "id") Integer id) {
        return Result.success(courseService.getById(id));
    }

}